//
//  RegisterViewController.m
//  Jingjing
//
//  Created by user on 15/11/9.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//

#import "RegisterViewController.h"
#import "RegistNextViewController.h"
@interface RegisterViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UITableView  *registTab;

@property(nonatomic,strong)NSArray      *placeHolderArr;
@property (nonatomic,strong) NSTimer    * timer;
@property (nonatomic,assign) int           statusInt;//计数-倒计时

@property(nonatomic,strong)UIButton    *nextBtn;
@property(nonatomic,strong)UIButton    *identifyBtn;//验证码

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _statusInt = 30;
  
     self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    [self createTheNavigationBar];
    [self createUI];
    
    if (!_placeHolderArr) {
        _placeHolderArr = @[@"请输入手机号",@"请输入验证码"];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];
    
    
}

#pragma mark -------------创建导航栏及相关控件
-(void)createTheNavigationBar
{
    
    //    自定义navgationBar
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"注册"];
    [self.view addSubview:topView];
    
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
    
    
    
    
}
- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self dismissViewControllerAnimated:TRUE completion:^(void){}];
}

-(void)createUI
{
    
    [self.view addSubview:self.registTab];
    [self.registTab addSubview:self.nextBtn];
}
-(UITableView *)registTab
{
    if (!_registTab) {
        _registTab = [[UITableView alloc] initWithFrame:CGRectMake(16.0f, 64.0f+16.0f, SCREEN_WIDTH-32.0f, SCREEN_HEIGHT-64.0f-16.0f) style:UITableViewStylePlain];
        _registTab.delegate = self;
        _registTab.dataSource = self;
        _registTab.rowHeight = 60.0f;
       _registTab.backgroundColor = [UIColor clearColor];
        _registTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _registTab;
}


//验证码按钮
-(UIButton *)identifyBtn
{
    if (!_identifyBtn) {
        _identifyBtn = [[UIButton  alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-88.0f-16.0f-16.0f,15.0f, 78.0f, 30.0f)];
        [_identifyBtn addTarget:self action:@selector(buttonIdentifyTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_identifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_identifyBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:14.0f]];
        _identifyBtn.backgroundColor = [UIColor lightGrayColor];
        _identifyBtn.enabled = NO;
        [_identifyBtn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_identifyBtn setBackgroundColor:kColorOrangePressed forState:UIControlStateHighlighted];
        [_identifyBtn setBackgroundColor:kColorOrangeDisabled forState:UIControlStateDisabled];
        [_identifyBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_identifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
        _identifyBtn.layer.cornerRadius = 5.0;
        _identifyBtn.layer.masksToBounds = YES;
    }
    return _identifyBtn;
}

//下一步按钮
-(UIButton *)nextBtn
{
    if (!_nextBtn) {
        _nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-32.0f)/2-(100.0f/2),152.0f,100.0f, 44.0f)];
        [_nextBtn addTarget:self action:@selector(buttonNextTapped) forControlEvents:UIControlEventTouchUpInside];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextBtn.layer.cornerRadius = 5;
        _nextBtn.layer.masksToBounds = YES;
        _nextBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
        [_nextBtn setBackgroundColor:kColorOrangeNormal forState:UIControlStateNormal];
        [_nextBtn setBackgroundColor:kColorOrangePressed forState:UIControlStateHighlighted];
        [_nextBtn setBackgroundColor:kColorOrangeDisabled forState:UIControlStateDisabled];
        _nextBtn.enabled = NO;
        
    }
    return _nextBtn;
}

#pragma mark-tableViewDelegate&datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.placeHolderArr.count;
}
static UITextField *__textField;//记录当前的textField
static UITextField *__textFieldPwd;//记录当前的textField
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        UIView * separtor = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 59.5f, SCREEN_WIDTH - 32.0f, 0.5)];
        separtor.backgroundColor =  [UIColor hexStringToColor:@"#bdbdbd"];
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
        
        UILabel *userlabel = [[UILabel alloc]initWithFrame:CGRectMake(24.0f, 5.0f, 80.0f, 45.0f)];
        userlabel.tag = 1000;
        userlabel.font = [UIFont systemFontOfSize:16.0f];
        userlabel.textColor = kColorTEXT;
        [cell.contentView addSubview:userlabel];
        
        
        
        UITextField *userTF = [[UITextField alloc] init];
        userTF.tag = 2000;
        userTF.delegate = self;
        userTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        userTF.keyboardType = UIKeyboardTypeNumberPad;
        [userTF setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        userTF.font = [UIFont systemFontOfSize:16.0f];
        userTF.textColor = kColorTEXT;
        [cell.contentView addSubview:userTF];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        
       
    }
    
    UILabel *userLabel = (UILabel*)[cell.contentView viewWithTag:1000];
    UITextField *text = (UITextField *)[cell.contentView viewWithTag:2000];
    text.placeholder = [_placeHolderArr objectAtIndex:indexPath.row];
    
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    if (indexPath.row==1) {
        separtor.hidden = YES;
    }else{
        separtor.hidden = NO;
    }

    
    if (indexPath.row==0) {
        userLabel.text = @"手机号";
        text.frame = CGRectMake(104.0f, 10.0f, SCREEN_WIDTH - 104.0f- 24.0f, 40.0f);
        __textField = text;
        [text addTarget:self action:@selector(identifTextFieldTapped:) forControlEvents:UIControlEventEditingChanged];
    }
    if (indexPath.row==1) {
        userLabel.text = @"验证码";
        __textFieldPwd = text;
        text.frame = CGRectMake(104.0f, 10.0f, SCREEN_WIDTH-16.0-88.0f-104.0f-16.0f, 40.0f);
        [text addTarget:self action:@selector(textFieldTapped:) forControlEvents:UIControlEventEditingChanged];
        [cell addSubview:self.identifyBtn];
        
    }
    
    return cell;
}

-(void)identifTextFieldTapped:(id)sender
{
    if ([AccountTools validatePhoneNumber:__textField.text]==YES) {
        _identifyBtn.enabled = YES;
        _identifyBtn.layer.borderWidth = 1.0;
        _identifyBtn.layer.borderColor = [[UIColor blackColor]CGColor];
    }else{
        _identifyBtn.enabled = NO;
        
    }
}

- (void)textFieldTapped:(id)sender
{
    
    
    if (__textFieldPwd.text.length == 6 && [AccountTools validatePhoneNumber:__textField.text]) {
        self.nextBtn.enabled = YES;
       
        
        
    }
    else
    {
        self.nextBtn.enabled = NO;
        
        
    }
    
}

#pragma mark-验证码按钮方法
- (void)buttonIdentifyTapped:(UIButton*)btn
{
    
    if (__textField.text.length>0) {
        if ([AccountTools validatePhoneNumber:__textField.text ]==YES) {
            
            _identifyBtn.enabled = FALSE;
            //   发送请求

            [AppGlobalClass PostDataWithNSstring:CHECKUSERCD withDictionary:@{@"userCd":__textField.text} success:^(NSDictionary *dictionary) {
                if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:NO]])
                {
                    
                    //获取成功开启定时器
                    if (!_timer)
                    {
                        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:TRUE];//开启定时器  倒计时结束后，在倒计时方法内使得按钮可以点击
                        [_timer fire];
                    }
                    [self getcheckcodeRequest];

                }
                else
                {
                   
                    ALERT_VIEW(@"该手机号码已经注册过");
                     _identifyBtn.enabled = TRUE;
                    
                }
                
                
            } failure:^(NSError *error) {
                _identifyBtn.enabled = TRUE;
            } networkerror:^(NSString *networkerror) {
                _identifyBtn.enabled = TRUE;
            }];
            
            
            
        }
        else
        {
            ALERT_VIEW(@"手机号不正确");
        }
    }
    else{
        ALERT_VIEW(@"手机号不能为空");
    }
}

- (void)getcheckcodeRequest
{
    //手机号码未注册过
    
    [AppGlobalClass PostDataWithNSstring:GETCHECKCODE withDictionary:@{@"mobileNumber":__textField.text} success:^(NSDictionary *dictionary) {
        
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            
        }
        else
        {
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
        }
        
        
    } failure:^(NSError *error) {
        
    } networkerror:^(NSString *networkerror) {
        
    }];

}
#pragma mark-下一步按钮方法
-(void)buttonNextTapped
{
    
    if ([AccountTools isEmpty:__textFieldPwd.text]==YES) {
        
        ALERT_VIEW(@"验证码输入不能为空")
        return;
    }
    
    [[AnimationIndicator sharedIndicator] startAnimationWithLoadText:@"加载中..."];
    [AppGlobalClass PostDataWithNSstring:VALIDATECHECKCODE withDictionary:@{@"mobileNumber":__textField.text,@"checkCode":__textFieldPwd.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            //验证码有效的情况下跳转
            RegistNextViewController *registNextVC = [[RegistNextViewController alloc]init];
            registNextVC.mobile = __textField.text;
            registNextVC.checkCode = __textFieldPwd.text;
            [self presentViewController:registNextVC animated:TRUE completion:^(void){}];
        }else
        {
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
            
        }
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];

    } failure:^(NSError *error) {
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];

        
    } networkerror:^(NSString *networkerror) {
        
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];

    }];
}

-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    
}
//时间倒计时
-(void)timeCounting
{
    
    _identifyBtn.enabled = NO;//点击后，让不可再点击
    
    
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
     _identifyBtn.layer.borderColor = [[UIColor clearColor]CGColor];
    [_identifyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    
    
    if ([phoneVersion doubleValue] >= 8.0) {
        [_identifyBtn setTitle:[NSString stringWithFormat:@"等待%ds",_statusInt] forState:UIControlStateNormal];
        
    }
    else{
        _identifyBtn.titleLabel.text = [NSString stringWithFormat:@"等待%ds",_statusInt] ;
        _identifyBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    if(_statusInt == 0)
    {
        [_identifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _statusInt = 30;
        _identifyBtn.enabled = TRUE;
        _identifyBtn.backgroundColor = [UIColor whiteColor];
        [_identifyBtn setTitleColor:kColorTEXT forState:UIControlStateNormal];
        _identifyBtn.layer.borderColor = [kColorTEXT CGColor];
        [_identifyBtn setBackgroundColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_timer invalidate];
        _timer = nil;
        return;//直接返回
    }
    _statusInt -=1;
    
}

//隐藏键盘
-(void)keyboardhide
{
    [__textFieldPwd resignFirstResponder];
    [__textField resignFirstResponder];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //解除键盘出现通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidShowNotification object:nil];
    //解除键盘隐藏通知
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name: UIKeyboardDidHideNotification object:nil];
}

//键盘下降
- (void)keyboardHide:(NSNotification *)noti
{
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    _registTab.contentOffset = CGPointMake(0, 0);
    
    [UIView commitAnimations];
}

//键盘升起
- (void)keyboardShow:(NSNotification *)noti
{
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:[[noti.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
    [UIView setAnimationCurve:7];
    if (keyboardFrame.origin.y != SCREEN_HEIGHT) {
        CGFloat a = _nextBtn.frame.origin.y+_nextBtn.frame.size.height+_registTab.frame.origin.y+80.0f;
        if (a < keyboardFrame.origin.y) {
            _registTab.contentOffset = CGPointMake(0, 0);
        }else
        {
            _registTab.contentOffset = CGPointMake(0, 80);
        }
        
    }
    
    [UIView commitAnimations];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

@end
